var util = require('../../../utils/util.js');
var ajax = require('../../../utils/ajax.js');
var common = require('../../../utils/common.js');
var PageBase = require('../../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    winHei: 0,
    dataLoaded: false,
    userInfo: {},
    goodsList: [],
    orderList: [{
      goodsprice: "",
      goodsname:"",
      num: "1",
      articlenumber: '',
      spec: '',
      code: '',
      unique: 'unique_0'
    }],
    index: 0,
    salesCode: [],
    totalPrice: 0,
    totalAmount: 0,
    checking: false,
    remark: '',
    focus: false,
    submiting: false
  },

  onLoad(options) {

    common.initApp({
      loginSuc: () => {
        this.setData({
          eid: app.getEmployeeid(),//员工id
          sid: app.getEmployeeSid(), //员工所属店铺id
          isShopLogin: !!app.getEmployeeid()
        });
        this._getList();
      }
    });

  },

  onShow() { 

  },

	/**
	 * 获取商品列表
	 * @return {[type]} [description]
	 */
  _getList() {

    ajax.G({
      url: 'm=goods',
      data: {
        size: 999,
        sid: this.data.sid
      },
      success: (res) => {
        var goodsList = res.data.item;
        //debugger;
        this.setData({
          goodsList
        });
        this._getSalesCode();
      }
    });

  },

  /**
   * 获取销售码
   */
  _getSalesCode: function () {
    var url = "m=shop&c=index&a=shopcode";
    var data = {
      sid: this.data.sid
    };
    var orderList = this.data.orderList;
    ajax.G({
      url,
      data,
      success: (data) => {
        var sales = data.data;
        var salesCode = [];
        for(var i = 0; i < sales.length;i ++){
          var code = sales[i].code;
          salesCode.push(code);
        };
        orderList[0].code = salesCode[0];
        this.setData({
          salesCode,
          dataLoaded: true
        })
      }
    })
  },
  /**
   *添加更多
   */
  _add: function (obj) {
    var orderList = this.data.orderList;
    var salesCode = this.data.salesCode;
    orderList.push({
      goodsname: obj.name || '',
      goodsprice: obj.price || '',
      articlenumber: obj.articlenumber || '',
      spec: obj.spec || '',
      num: obj.num || '',
      code: '',
    });
    console.log(orderList);
    orderList[orderList.length - 1].unique = orderList[orderList.length - 2].unique.split('_')[0] + '_' + parseInt(parseInt(orderList[orderList.length - 2].unique.split('_')[1]) + 1);
    orderList[orderList.length - 1].code = salesCode[0];
    console.log(orderList);
    this.setData({
      orderList
    });
    this._submitOrder()
  },
  /**
   *删除
   */
  _del: function (evt) {
    var orderList = this.data.orderList;
    var index = evt.currentTarget.dataset.index;
    if (orderList.length == 1) {
      util.alert("最少保留一个");
      return false;
    }
    orderList.splice(index, 1);
    this.setData({
      orderList
    });
    this._submitOrder();
  },
  /**
   * input框失去焦点时候，获取value
   */
  _isNameEntry: function (evt) {
    this.setCurrentData(evt, 'goodsname');
  },
  _isPriceEntry: function (evt) {
    //debugger;
    this.setCurrentData(evt, 'goodsprice');
  },
  _isAmountEntry: function (evt) {
    this.setCurrentData(evt, 'num');
  },
  _isGoodNumEntry: function (evt) {
    this.setCurrentData(evt, 'articlenumber');
  },
  _isOrderSkuEntry: function (evt) {
    this.setCurrentData(evt, 'spec');
  },
  /**
   * 切换销售码
   */
  _tabSwitch: function (evt) {
    var {
      current,
      index
        } = evt.currentTarget.dataset;
    var orderList = this.data.orderList;
    var salesCode = this.data.salesCode;
    orderList[index].currentTab = current;
    orderList[index].code = salesCode[current];
    this.setData({
      orderList
    })
  },
  /**
   * 失去焦点时候，获取备注value
   */
  _confirmRemark: function (evt) {
    this.setData({
      remark: evt.detail.value
    });
  },


  // 选择商品
  _chooseGoods: function(evt){
      //debugger;
      var obj = evt.currentTarget.dataset;
      this._add(obj);
  },
  /**
   * 计算价格
   */
  _submitOrder: function () {
    //debugger;
    var orderList = this.data.orderList;
    var totalPrice = 0, totalAmount = 0;
    this.isWrong = false;
    orderList.forEach((item) => {
      // if (item.price == '') {
      //   util.alert('您输入的价格不能为空');
      //   this.isWrong = true;
      // } else if (item.price == 0) {
      //   util.alert('您输入的价格不能为0');
      //   this.isWrong = true;
      // } else if (item.amount == '') {
      //   util.alert('您输入的数量不能为空');
      //   this.isWrong = true;
      // } else if (item.amount == 0) {
      //   util.alert('您输入的数量不能为0');
      //   this.isWrong = true;
      // } 
      var price = Number(item.goodsprice) * parseInt(item.num) || 0;
      totalPrice = totalPrice + price;
      totalAmount += parseInt(item.num) || 0;
    })

    if (this.isWrong) {
      return false;
    }
    console.log(totalAmount,totalPrice)
    this.setData({
      totalAmount,
      checking: true,
      totalPrice: totalPrice.toFixed(2)
    })

  },

  /**
   * 取消模态框提醒
   */
  // _cancel: function () {
  //   if (this.data.submiting) {
  //     util.alert('正在提交中，请稍后...');
  //     return false;
  //   }
  //   this.setData({
  //     checking: false,
  //     totalPrice: 0,
  //     totalAmount: 0
  //   })
  // },
  /**
   * 确认提交订单信息
   */
  _confirm: function () {
    //debugger;
    var orderList = this.data.orderList;
    var remark = this.data.remark;
    //深拷贝，把orderList赋值给goods，指向不同的引用
    var goods = JSON.parse(JSON.stringify(orderList));

    goods.forEach((item) => {
      delete item.unique;
    })

    //goods = JSON.stringify(goods);

    var url = 'm=store&c=order&a=add';
    var data = {
      staffid: this.data.eid,
      sid: this.data.sid,
      orders: goods,
      remark
    }

    if (this.data.submiting) {
      util.alert('正在提交中，请稍后...');
      return false;
    }

    this.setData({
      submiting: true
    })

    ajax.P({
      url,
      data,
      success: (data) => {
        //var order_id = data.result.order_id;
        this.setData({
          checking: false,
          submiting: false
        });
        if (data.code == 1) {
          util.showWarn(data.msg);
          return;
        }
        wx.redirectTo({
          url: '/pages/shop/payOrderList/index?sid=' + this.data.sid
        })
      },
      fail: (data) => {
        this.setData({
          submiting: false
        })
      }
    })
  },

  setCurrentData: function (evt, item) {
    //debugger;
    var orderList = this.data.orderList;
    var index = evt.currentTarget.dataset.index;
    orderList[index][item] = evt.detail.value;
    this.setData({
      orderList
    });
    this._submitOrder();
  }
}));